package com.ivan.dao;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.ivan.beans.Message;
import com.ivan.beans.ChatUser;

public class MessageDao{

	/**
	 * 	Save new Message Object, or Update current existing Message
	 * @return
	 */
	public boolean saveOrUpdateMessage(Message message){
		boolean isSuccess = false;
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try{
			pm.makePersistent(message);
			isSuccess = true;
		} finally {
			pm.close();
		}
		return isSuccess;
	}
	
	/**
	 * Get all messages 
	 * @return
	 */
	public List<Message> getAllMessagesUnderUser(ChatUser user){
		List<Message> messages = new ArrayList<Message>();
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(Message.class);
		query.setFilter("fromUser = userKey");
		query.declareParameters("String userKey");
		messages = (List<Message>) query.execute(user.getId());
		return messages;
	}
	
	public static void main(String[] args){
		ChatUser from = new ChatUser();
		from.setName("A");
		from.setPassword("Apwd");
		ChatUser to = new ChatUser();
		to.setName("B");
		to.setPassword("Bpwd");
		Message msg = new Message();
		msg.setFromUser(from.getEmail());
		msg.setToUser(to.getEmail());
		MessageDao dao = new MessageDao();
		dao.saveOrUpdateMessage(msg);
	}
	
}
